package com.yxhl.zoume.core.user.ui.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding.view.RxView;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.yxhl.zoume.R;
import com.yxhl.zoume.account.event.LoginStatus;
import com.yxhl.zoume.account.event.LoginViewBackEvent;
import com.yxhl.zoume.common.ui.fragment.BaseFragment;
import com.yxhl.zoume.core.user.presenter.FeedbackPresenter;
import com.yxhl.zoume.core.user.ui.activity.UserContainerActivity;
import com.yxhl.zoume.core.user.view.FeedbackView;
import com.yxhl.zoume.di.component.usercenter.DaggerUserCenterComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.domain.interactor.ZMSubscriber;
import com.yxhl.zoume.utils.PromptUtils;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

public class FeedbackFragment extends BaseFragment implements FeedbackView {

    @BindView(R.id.et_feedback_input)
    EditText mEtFeedbackInput;

    @BindView(R.id.tv_feedback_count)
    TextView mTvFeedbackCount;

    @BindView(R.id.btn_feedback_commit)
    Button mBtnFeedbackCommit;

    MaterialDialog dialogForWaitingDetail = null;
    @Inject
    FeedbackPresenter mFeedbackPresenter;

    private LoginStatus isLogin = LoginStatus.LOGIN;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onRxBusEvent();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mFeedbackPresenter.attachView(this);
        feedbackControl();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (isLogin == LoginStatus.LOGIN) {
            mFeedbackPresenter.detectionLogin();
        }
        if (isLogin == LoginStatus.NOT_LOGIN) {
            getActivity().onBackPressed();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mFeedbackPresenter.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mFeedbackPresenter.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mFeedbackPresenter.onDestroy();
    }

    public static FeedbackFragment newInstance() {
        FeedbackFragment fragment = new FeedbackFragment();
        return fragment;
    }

    private void onRxBusEvent() {
        getSubscription().add(toSubscription(LoginViewBackEvent.class, new Action1<LoginViewBackEvent>() {
            @Override
            public void call(LoginViewBackEvent loginViewBackEvent) {
                isLogin = loginViewBackEvent.getIsLogin();

            }
        }));
    }

    private void feedbackControl() {

        Observable<Boolean> feedbackObservable = RxTextView.textChanges(mEtFeedbackInput)
                .map(new Func1<CharSequence, Boolean>() {
                    @Override
                    public Boolean call(CharSequence charSequence) {
                        int length = charSequence.toString().length();
                        mTvFeedbackCount.setText(140 - length + "/140");
                        if (length == 140) {
                            PromptUtils.showShort(mActivity, "最多输入140个字");
                        }
                        return length > 0 && length <= 140;
                    }
                })
                .skip(1);

        feedbackObservable.subscribe(new ZMSubscriber<Boolean>() {
            @Override
            public void onNext(Boolean isEnabled) {
                mBtnFeedbackCommit.setEnabled(isEnabled);
            }
        });

        RxView.clicks(mBtnFeedbackCommit).throttleFirst(3, TimeUnit.SECONDS)
                .subscribe(new Action1<Void>() {
                    @Override
                    public void call(Void aVoid) {
                        feedbackCommit();
                    }
                });

    }

    private void feedbackCommit() {
        showWaitingDialog(true);
        mFeedbackPresenter.commitFeedback(mEtFeedbackInput.getText().toString().trim());
    }


    @Override
    protected void initializeInjector() {
        DaggerUserCenterComponent
                .builder()
                .activityModule(new ActivityModule(mActivity))
                .appComponent(getAppComponent())
                .build()
                .inject(this);

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_user_center_feedback;
    }

    @Override
    protected void setupToolBar() {
        ((UserContainerActivity) mActivity).setToolbarTitle("意见反馈");
    }


    @Override
    public void renderFeedbackOnSuccess() {
        mEtFeedbackInput.setText("");
        showWaitingDialog(false);
        PromptUtils.showShort(mActivity, "意见反馈成功，感谢您的支持。");
    }

    @Override
    public void renderFeedbackOnFailure(String errorMessage) {
        showWaitingDialog(false);
        PromptUtils.showShort(mActivity, errorMessage);
    }

    @Override
    public void renderFeedbackOnError(String message) {
        showWaitingDialog(false);
        PromptUtils.showShort(mActivity, message);
    }

    public void showWaitingDialog(boolean isWaiting) {
        if (isWaiting) {
            dialogForWaitingDetail = new MaterialDialog.Builder(mActivity)
                    .content(R.string.dialog_waiting_processing)
                    .progress(true, 0)
                    .canceledOnTouchOutside(false)
                    .show();
        } else {
            if (null != dialogForWaitingDetail) {
                dialogForWaitingDetail.dismiss();
            }
        }
    }
}
